using System;
using System.Collections;
using System.Text;

using log4net;
using log4net.Config;

using MySql.Data.MySqlClient;
using Chat.metier;
using ChatServer;
using NHibernate;

namespace Chat.dao
{
    class MessageDAO : IMessageDAO
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(MessageDAO));

        #region IMessageDAO Membres
        /// <summary>
        /// Retourne un user en fonction de son id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Message getById(int id)
        {
                ISession session = InitFramework.sessionFactory.OpenSession();
                try
                {
                    Message message = (Message)session.Get(typeof(Message), id);
                    session.Close();
                    return message;
                }
            catch (Exception e)
            {
                log.Error("Message getById ", e);
                return null;
            }
        }

        /// <summary>
        /// Retourne tous les utilisateurs
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IList getAll()
        {
                ISession session = InitFramework.sessionFactory.OpenSession();
                try
                {
                    IList messages = session.CreateQuery("from Message").List();
                    session.Close();
                    return messages;
                }
            
            catch (Exception e)
            {
                log.Error("Message getAll", e);
                return null;
            }
        }

        /// <summary>
        /// Save a message for a User to his Contact
        /// </summary>
        /// <param name="IdUser"></param>
        /// <param name="IdContact"></param>
        /// <param name="Message"></param>
        public void saveMessage(int IdUser, int IdContact, String Message)
        {
            IUserDAO uDAO = (IUserDAO)InitFramework.springCtx.GetObject("user.dao");
            User u = uDAO.getById(IdUser);
            User c = uDAO.getById(IdContact);

            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                ITransaction tx = session.BeginTransaction();

                Message m = new Message();
                m.Sender = u;
                m.Receiver = c;
                m.Date = DateTime.Now;
                m.MessageText = Message;
                session.Save(m);
                tx.Commit();
                session.Close();
            }
            catch (Exception e1)
            {
                log.Error("erreur dans MessageDAO.saveMessage() ", e1);
            }
        }

        #endregion
    }
}
